package com.syqc.monitor.ui.carmonitor

import autodispose2.autoDispose
import com.amap.api.maps.AMap
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.LatLngBounds
import com.syqc.comlib.AppConfigs
import com.syqc.comlib.UserConstant
import com.syqc.comlib.auto.AutoDisposeViewModel
import com.syqc.comlib.utils.CacheMMKV
import com.syqc.comlib.utils.GsonUtil
import com.syqc.entity.Driver
import com.syqc.entity.GpsDetail
import com.syqc.entity.Legend
import com.syqc.entity.VideosPass
import com.syqc.maps.utils.MarkerSet
import com.syqc.monitor.R
import com.syqc.net.ServiceHelper
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.subjects.PublishSubject
import java.util.concurrent.TimeUnit

/** @Author Jasper @Time 2020/7/31 @Desc 地图 */
class CarMapViewModel : AutoDisposeViewModel() {
    var gpsDetail: GpsDetail? = null

    //是否处于显示状态
    var isHidden = false

    //对讲通道号
    var talkChannel = ""

    var isShow
        get() = CacheMMKV.decodeBooleanSave("car_isShow", true)
        set(value) = CacheMMKV.encodeSave("car_isShow", value)

    //是否是车牌展示
    var isPlate: Boolean = MarkerSet.localSet.showPlate

    var mMapType: Int
        get() = CacheMMKV.decodeInt("car_isMapNormal", AMap.MAP_TYPE_NORMAL)
        set(value) = CacheMMKV.encode("car_isMapNormal", value)

    var isCarTraffic: Boolean
        get() = CacheMMKV.decodeBoolean("car_isCarTraffic", true)
        set(value) = CacheMMKV.encode("car_isCarTraffic", value)

    val locationSub: PublishSubject<GpsDetail> = PublishSubject.create()
    val legendSub: PublishSubject<MutableList<Legend>> = PublishSubject.create()


    var carId: String? = null
        set(value) {
            if (value != null && !isHidden) {
                startTime(value)
            }
            field = value
        }

    /** 获取定位信息 */
    private fun getLocation(carId: String?) {
        if (carId.isNullOrEmpty()) {
            toast(R.string.hint_toast_choose_car)
            stopTime()
        } else
            ServiceHelper.getRepository().getGpsRInfo("", carId)
                .autoDispose(this)
                .subscribe({
                    if (it.isNullOrEmpty()) {
                        toast(R.string.toast_no_location_msg)
                        stopTime()
                        driverInfo.clear()
                        gpsDetail = null
                    } else {
                        gpsDetail = it[0]
                        handlePhone(gpsDetail!!)
                        locationSub.onNext(gpsDetail!!)
                    }
                }, error)
    }

    /** 获取定位信息 */
    private fun getLocation2(carId: String?) {
        if (carId.isNullOrEmpty()) {
            toast(R.string.hint_toast_choose_car)
            stopTime()
        } else
            ServiceHelper.getRepository().getGpsRInfo("", carId)
                .autoDispose(this)
                .subscribe({
                    if (it.isNullOrEmpty()) {
                        toast(R.string.toast_no_location_msg)
                        stopTime()
                        driverInfo.clear()
                        gpsDetail = null
                    } else {
                        toast(R.string.toast_refresh_success)
                        gpsDetail = it[0]
                        handlePhone(gpsDetail!!)
                        locationSub.onNext(gpsDetail!!)
                    }
                }, error)
    }

    //司机数据
    val driverInfo = mutableListOf<Driver>()
    private fun handlePhone(carInfo: GpsDetail) {
        driverInfo.clear()
        val drvPhone = carInfo.drvPhone
        if (drvPhone.isNotEmpty() && carInfo.drvName.isNotEmpty()) {
            driverInfo.clear()
            val phones = drvPhone.split(",")
            val names = carInfo.drvName.split(",")
            for (i in phones.indices) {
                driverInfo.add(Driver(names[i], phones[i]))
            }
        }

        talkChannel = getAudioChannel()
    }

    /** 获取图例 */
    fun getLegend(carId: String?) {
        if (carId.isNullOrEmpty()) {
            toast(R.string.hint_toast_choose_car)
            return
        }
        toastLoading(true)
        ServiceHelper.getRepository().getLegend(carId).autoDispose(this).subscribe({
            if (it.isNullOrEmpty()) {
                toast(R.string.toast_car_no_legend)
            } else {
                if (UserConstant.current_ip == "113.105.152.93") {
                    val filter = it.filter { legend ->
                        legend.stateIndex != "6"
                    }.toMutableList()
                    legendSub.onNext(filter)
                } else {
                    legendSub.onNext(it)
                }
            }
            toastLoading(false)
        }, error)
    }

    private var subscribe: Disposable? = null
    private fun getRefresh(): Int = AppConfigs.mapRefresh


    /** 开始请求 */
    fun startTime(carId: String) {
        stopTime()
        nowTime = getRefresh()
        timeSub.onNext(nowTime)
        getLocation(carId)
        subscribe = Flowable.interval(0, 1, TimeUnit.SECONDS)
            .autoDispose(this)
            .subscribe {
                if (nowTime == 1) {
                    nowTime = getRefresh()
                } else {
                    nowTime--
                }
                timeSub.onNext(nowTime)
                if (nowTime == 1) {
                    getLocation(carId)
                }
            }
    }

    //刷新时间
    private var nowTime = getRefresh()
    private val timeSub by lazy { PublishSubject.create<Int>() }
    fun timeObserver() = timeSub.hide()


    fun refresh() {
        getLocation(carId)
    }

    fun refresh2() {
        getLocation2(carId)
    }

    /** 停止请求 */
    fun stopTime() {
        subscribe?.dispose()
    }

    /** 计算LatLngBounds */
    fun setBounds(vararg latLng: LatLng): LatLngBounds {
        val builder = LatLngBounds.builder()
        for (item in latLng) {
            builder.include(item)
        }
        return builder.build()
    }

    /**
     * 获取对讲通道号
     *
     * @return
     */
    private fun getAudioChannel(): String {
        if (gpsDetail?.videos == null) return ""
        var talkChannel = ""
        gpsDetail?.run {
            val entity = GsonUtil.formObject<VideosPass>(videos)
            val channel = entity.tc
            talkChannel = if (channel.isNullOrEmpty()) {
                val passEntitys = entity.vs?.split(",")
                if (passEntitys.isNullOrEmpty()) {
                    ""
                } else {
                    val passInfos = passEntitys[0].split(":");
                    passInfos[0]
                }
            } else {
                channel
            }
        }
        return talkChannel
    }


}
